documentation
[lhc/web/wiklou.git] / includes / DifferenceEngine.php
1 <?php
2 /**
3 * See diff.doc
4 * @package MediaWiki
5 * @subpackage DifferenceEngine
6 */
7
8 /** */
9 require_once( 'Revision.php' );
10
11 define( 'MAX_DIFF_LINE', 10000 );
12 define( 'MAX_DIFF_XREF_LENGTH', 10000 );
13
14 /**
15 * @todo document
16 * @access public
17 * @package MediaWiki
18 * @subpackage DifferenceEngine
19 */
20 class DifferenceEngine {
21 /**#@+
22 * @access private
23 */
24 var $mOldid, $mNewid, $mTitle;
25 var $mOldtitle, $mNewtitle, $mPagetitle;
26 var $mOldtext, $mNewtext;
27 var $mOldPage, $mNewPage;
28 var $mRcidMarkPatrolled;
29 var $mOldRev, $mNewRev;
30 var $mRevisionsLoaded = false; // Have the revisions been loaded
31 var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2?
32 /**#@-*/
33
34 /**
35 * Constructor
36 * @param Title $titleObj Title object that the diff is associated with
37 * @param integer $old Old ID we want to show and diff with.
38 * @param string $new Either 'prev' or 'next'.
39 * @param integer $rcid ??? (default 0)
40 */
41 function DifferenceEngine( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) {
42 $this->mTitle = $titleObj;
43 wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n");
44
45 if ( 'prev' === $new ) {
46 # Show diff between revision $old and the previous one.
47 # Get previous one from DB.
48 #
49 $this->mNewid = intval($old);
50
51 $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid );
52
53 } elseif ( 'next' === $new ) {
54 # Show diff between revision $old and the previous one.
55 # Get previous one from DB.
56 #
57 $this->mOldid = intval($old);
58 $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid );
59 if ( false === $this->mNewid ) {
60 # if no result, NewId points to the newest old revision. The only newer
61 # revision is cur, which is "0".
62 $this->mNewid = 0;
63 }
64
65 } else {
66 $this->mOldid = intval($old);
67 $this->mNewid = intval($new);
68 }
69 $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer
70 }
71
72 function showDiffPage() {
73 global $wgUser, $wgOut, $wgContLang, $wgUseExternalEditor, $wgUseRCPatrol;
74 $fname = 'DifferenceEngine::showDiffPage';
75 wfProfileIn( $fname );
76
77 # If external diffs are enabled both globally and for the user,
78 # we'll use the application/x-external-editor interface to call
79 # an external diff tool like kompare, kdiff3, etc.
80 if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) {
81 global $wgInputEncoding,$wgServer,$wgScript,$wgLang;
82 $wgOut->disable();
83 header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding );
84 $url1=$this->mTitle->getFullURL("action=raw&oldid=".$this->mOldid);
85 $url2=$this->mTitle->getFullURL("action=raw&oldid=".$this->mNewid);
86 $special=$wgLang->getNsText(NS_SPECIAL);
87 $control=<<<CONTROL
88 [Process]
89 Type=Diff text
90 Engine=MediaWiki
91 Script={$wgServer}{$wgScript}
92 Special namespace={$special}
93
94 [File]
95 Extension=wiki
96 URL=$url1
97
98 [File 2]
99 Extension=wiki
100 URL=$url2
101 CONTROL;
102 echo($control);
103 return;
104 }
105
106 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
107 "{$this->mNewid})";
108 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
109
110 $wgOut->setArticleFlag( false );
111 if ( ! $this->loadRevisionData() ) {
112 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
113 $wgOut->addWikitext( $mtext );
114 wfProfileOut( $fname );
115 return;
116 }
117 if ( $this->mNewRev->isCurrent() ) {
118 $wgOut->setArticleFlag( true );
119 }
120
121 # mOldid is false if the difference engine is called with a "vague" query for
122 # a diff between a version V and its previous version V' AND the version V
123 # is the first version of that article. In that case, V' does not exist.
124 if ( $this->mOldid === false ) {
125 $this->showFirstRevision();
126 wfProfileOut( $fname );
127 return;
128 }
129
130 $wgOut->suppressQuickbar();
131
132 $oldTitle = $this->mOldPage->getPrefixedText();
133 $newTitle = $this->mNewPage->getPrefixedText();
134 if( $oldTitle == $newTitle ) {
135 $wgOut->setPageTitle( $newTitle );
136 } else {
137 $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle );
138 }
139 $wgOut->setSubtitle( wfMsg( 'difference' ) );
140 $wgOut->setRobotpolicy( 'noindex,follow' );
141
142 if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) {
143 $wgOut->loginToUse();
144 $wgOut->output();
145 wfProfileOut( $fname );
146 exit;
147 }
148
149 $sk = $wgUser->getSkin();
150 $talk = $wgContLang->getNsText( NS_TALK );
151 $contribs = wfMsg( 'contribslink' );
152
153 if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) {
154 $username = $this->mNewRev->getUserText();
155 $rollback = '&nbsp;&nbsp;&nbsp;<strong>[' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'rollbacklink' ),
156 'action=rollback&from=' . urlencode( $username ) .
157 '&token=' . urlencode( $wgUser->editToken( array( $this->mTitle->getPrefixedText(), $username ) ) ) ) .
158 ']</strong>';
159 } else {
160 $rollback = '';
161 }
162 if( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isAllowed( 'patrol' ) ) {
163 $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']';
164 } else {
165 $patrol = '';
166 }
167
168 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ),
169 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' );
170 if ( $this->mNewRev->isCurrent() ) {
171 $nextlink = '';
172 } else {
173 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ),
174 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
175 }
176
177 $oldHeader = "<strong>{$this->mOldtitle}</strong><br />" .
178 $sk->revUserTools( $this->mOldRev ) . "<br />" .
179 $sk->revComment( $this->mOldRev ) . "<br />" .
180 $prevlink;
181 $newHeader = "<strong>{$this->mNewtitle}</strong><br />" .
182 $sk->revUserTools( $this->mNewRev ) . " $rollback<br />" .
183 $sk->revComment( $this->mNewRev ) . "<br />" .
184 $nextlink . $patrol;
185
186 $this->showDiff( $oldHeader, $newHeader );
187 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
188
189 if( !$this->mNewRev->isCurrent() ) {
190 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
191 }
192
193 $this->loadNewText();
194 if( is_object( $this->mNewRev ) ) {
195 $wgOut->setRevisionId( $this->mNewRev->getId() );
196 }
197 $wgOut->addSecondaryWikiText( $this->mNewtext );
198
199 if( !$this->mNewRev->isCurrent() ) {
200 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
201 }
202
203 wfProfileOut( $fname );
204 }
205
206 /**
207 * Show the first revision of an article. Uses normal diff headers in
208 * contrast to normal "old revision" display style.
209 */
210 function showFirstRevision() {
211 global $wgOut, $wgUser;
212
213 $fname = 'DifferenceEngine::showFirstRevision';
214 wfProfileIn( $fname );
215
216 # Get article text from the DB
217 #
218 if ( ! $this->loadNewText() ) {
219 $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " .
220 "{$this->mNewid})";
221 $mtext = wfMsg( 'missingarticle', "<nowiki>$t</nowiki>" );
222 $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) );
223 $wgOut->addWikitext( $mtext );
224 wfProfileOut( $fname );
225 return;
226 }
227 if ( $this->mNewRev->isCurrent() ) {
228 $wgOut->setArticleFlag( true );
229 }
230
231 # Check if user is allowed to look at this page. If not, bail out.
232 #
233 if ( !( $this->mTitle->userCanRead() ) ) {
234 $wgOut->loginToUse();
235 $wgOut->output();
236 wfProfileOut( $fname );
237 exit;
238 }
239
240 # Prepare the header box
241 #
242 $sk = $wgUser->getSkin();
243
244 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' );
245 $header = "<div class=\"firstrevisionheader\" style=\"text-align: center\"><strong>{$this->mOldtitle}</strong><br />" .
246 $sk->revUserTools( $this->mNewRev ) . "<br />" .
247 $sk->revComment( $this->mNewRev ) . "<br />" .
248 $nextlink . "</div>\n";
249
250 $wgOut->addHTML( $header );
251
252 $wgOut->setSubtitle( wfMsg( 'difference' ) );
253 $wgOut->setRobotpolicy( 'noindex,nofollow' );
254
255
256 # Show current revision
257 #
258 $wgOut->addHTML( "<hr /><h2>{$this->mPagetitle}</h2>\n" );
259 if( is_object( $this->mNewRev ) ) {
260 $wgOut->setRevisionId( $this->mNewRev->getId() );
261 }
262 $wgOut->addSecondaryWikiText( $this->mNewtext );
263
264 wfProfileOut( $fname );
265 }
266
267 /**
268 * Get the diff text, send it to $wgOut
269 * Returns false if the diff could not be generated, otherwise returns true
270 */
271 function showDiff( $otitle, $ntitle ) {
272 global $wgOut;
273 $diff = $this->getDiff( $otitle, $ntitle );
274 if ( $diff === false ) {
275 $wgOut->addWikitext( wfMsg( 'missingarticle', "<nowiki>(fixme, bug)</nowiki>" ) );
276 return false;
277 } else {
278 $wgOut->addHTML( $diff );
279 return true;
280 }
281 }
282
283 /**
284 * Get diff table, including header
285 * Note that the interface has changed, it's no longer static.
286 * Returns false on error
287 */
288 function getDiff( $otitle, $ntitle ) {
289 $body = $this->getDiffBody();
290 if ( $body === false ) {
291 return false;
292 } else {
293 return $this->addHeader( $body, $otitle, $ntitle );
294 }
295 }
296
297 /**
298 * Get the diff table body, without header
299 * Results are cached
300 * Returns false on error
301 */
302 function getDiffBody() {
303 global $wgMemc, $wgDBname;
304 $fname = 'DifferenceEngine::getDiffBody';
305 wfProfileIn( $fname );
306
307 // Cacheable?
308 $key = false;
309 if ( $this->mOldid && $this->mNewid ) {
310 // Try cache
311 $key = "$wgDBname:diff:oldid:{$this->mOldid}:newid:{$this->mNewid}";
312 $difftext = $wgMemc->get( $key );
313 if ( $difftext ) {
314 wfIncrStats( 'diff_cache_hit' );
315 $difftext = $this->localiseLineNumbers( $difftext );
316 $difftext .= "\n<!-- diff cache key $key -->\n";
317 wfProfileOut( $fname );
318 return $difftext;
319 }
320 }
321
322 if ( !$this->loadText() ) {
323 wfProfileOut( $fname );
324 return false;
325 }
326
327 $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext );
328
329 // Save to cache for 7 days
330 if ( $key !== false && $difftext !== false ) {
331 wfIncrStats( 'diff_cache_miss' );
332 $wgMemc->set( $key, $difftext, 7*86400 );
333 } else {
334 wfIncrStats( 'diff_uncacheable' );
335 }
336 // Replace line numbers with the text in the user's language
337 if ( $difftext !== false ) {
338 $difftext = $this->localiseLineNumbers( $difftext );
339 }
340 wfProfileOut( $fname );
341 return $difftext;
342 }
343
344 /**
345 * Generate a diff, no caching
346 * $otext and $ntext must be already segmented
347 */
348 function generateDiffBody( $otext, $ntext ) {
349 global $wgExternalDiffEngine, $wgContLang;
350 $fname = 'DifferenceEngine::generateDiffBody';
351
352 $otext = str_replace( "\r\n", "\n", $otext );
353 $ntext = str_replace( "\r\n", "\n", $ntext );
354
355 if ( $wgExternalDiffEngine == 'wikidiff' ) {
356 # For historical reasons, external diff engine expects
357 # input text to be HTML-escaped already
358 $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) );
359 $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) );
360 if( !function_exists( 'wikidiff_do_diff' ) ) {
361 dl('php_wikidiff.so');
362 }
363 return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) );
364 }
365
366 if ( $wgExternalDiffEngine == 'wikidiff2' ) {
367 # Better external diff engine, the 2 may some day be dropped
368 # This one does the escaping and segmenting itself
369 if ( !function_exists( 'wikidiff2_do_diff' ) ) {
370 @dl('php_wikidiff2.so');
371 }
372 if ( function_exists( 'wikidiff2_do_diff' ) ) {
373 return wikidiff2_do_diff( $otext, $ntext, 2 );
374 }
375 }
376 if ( $wgExternalDiffEngine !== false ) {
377 # Diff via the shell
378 global $wgTmpDirectory;
379 $tempName1 = tempnam( $wgTmpDirectory, 'diff_' );
380 $tempName2 = tempnam( $wgTmpDirectory, 'diff_' );
381
382 $tempFile1 = fopen( $tempName1, "w" );
383 if ( !$tempFile1 ) {
384 wfProfileOut( $fname );
385 return false;
386 }
387 $tempFile2 = fopen( $tempName2, "w" );
388 if ( !$tempFile2 ) {
389 wfProfileOut( $fname );
390 return false;
391 }
392 fwrite( $tempFile1, $otext );
393 fwrite( $tempFile2, $ntext );
394 fclose( $tempFile1 );
395 fclose( $tempFile2 );
396 $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 );
397 wfProfileIn( "$fname-shellexec" );
398 $difftext = wfShellExec( $cmd );
399 wfProfileOut( "$fname-shellexec" );
400 unlink( $tempName1 );
401 unlink( $tempName2 );
402 return $difftext;
403 }
404
405 # Native PHP diff
406 $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) );
407 $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) );
408 $diffs =& new Diff( $ota, $nta );
409 $formatter =& new TableDiffFormatter();
410 return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) );
411 }
412
413
414 /**
415 * Replace line numbers with the text in the user's language
416 */
417 function localiseLineNumbers( $text ) {
418 return preg_replace_callback( '/<!--LINE (\d+)-->/',
419 array( &$this, 'localiseLineNumbersCb' ), $text );
420 }
421
422 function localiseLineNumbersCb( $matches ) {
423 global $wgLang;
424 return wfMsg( 'lineno', $wgLang->formatNum( $matches[1] ) );
425 }
426
427 /**
428 * Add the header to a diff body
429 */
430 function addHeader( $diff, $otitle, $ntitle ) {
431 $out = "
432 <table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>
433 <tr>
434 <td colspan='2' width='50%' align='center' class='diff-otitle'>{$otitle}</td>
435 <td colspan='2' width='50%' align='center' class='diff-ntitle'>{$ntitle}</td>
436 </tr>
437 $diff
438 </table>
439 ";
440 return $out;
441 }
442
443 /**
444 * Use specified text instead of loading from the database
445 */
446 function setText( $oldText, $newText ) {
447 $this->mOldtext = $oldText;
448 $this->mNewtext = $newText;
449 $this->mTextLoaded = 2;
450 }
451
452 /**
453 * Load revision metadata for the specified articles. If newid is 0, then compare
454 * the old article in oldid to the current article; if oldid is 0, then
455 * compare the current article to the immediately previous one (ignoring the
456 * value of newid).
457 *
458 * If oldid is false, leave the corresponding revision object set
459 * to false. This is impossible via ordinary user input, and is provided for
460 * API convenience.
461 */
462 function loadRevisionData() {
463 global $wgLang;
464 if ( $this->mRevisionsLoaded ) {
465 return true;
466 } else {
467 // Whether it succeeds or fails, we don't want to try again
468 $this->mRevisionsLoaded = true;
469 }
470
471 // Load the new revision object
472 if( $this->mNewid ) {
473 $this->mNewRev = Revision::newFromId( $this->mNewid );
474 } else {
475 $this->mNewRev = Revision::newFromTitle( $this->mTitle );
476 }
477
478 if( is_null( $this->mNewRev ) ) {
479 return false;
480 }
481
482 // Set assorted variables
483 if( $this->mNewRev->isCurrent() ) {
484 $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) );
485 $this->mNewPage = $this->mTitle;
486 $newLink = $this->mNewPage->escapeLocalUrl();
487 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
488 } else {
489 $this->mNewPage = $this->mNewRev->getTitle();
490 $newLink = $this->mNewPage->escapeLocalUrl ('oldid=' . $this->mNewid );
491 $t = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true );
492 $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $t ) );
493 $this->mNewtitle = "<a href='$newLink'>{$this->mPagetitle}</a>";
494 }
495
496 // Load the old revision object
497 $this->mOldRev = false;
498 if( $this->mOldid ) {
499 $this->mOldRev = Revision::newFromId( $this->mOldid );
500 } elseif ( $this->mOldid === 0 ) {
501 $rev = $this->mNewRev->getPrevious();
502 if( $rev ) {
503 $this->mOldid = $rev->getId();
504 $this->mOldRev = $rev;
505 } else {
506 // No previous revision; mark to show as first-version only.
507 $this->mOldid = false;
508 $this->mOldRev = false;
509 }
510 }/* elseif ( $this->mOldid === false ) leave mOldRev false; */
511
512 if( is_null( $this->mOldRev ) ) {
513 return false;
514 }
515
516 if ( $this->mOldRev ) {
517 $this->mOldPage = $this->mOldRev->getTitle();
518
519 $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true );
520 $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid );
521 $this->mOldtitle = "<a href='$oldLink'>" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) . '</a>';
522 }
523
524 return true;
525 }
526
527 /**
528 * Load the text of the revisions, as well as revision data.
529 */
530 function loadText() {
531 if ( $this->mTextLoaded == 2 ) {
532 return true;
533 } else {
534 // Whether it succeeds or fails, we don't want to try again
535 $this->mTextLoaded = 2;
536 }
537
538 if ( !$this->loadRevisionData() ) {
539 return false;
540 }
541 if ( $this->mOldRev ) {
542 // FIXME: permission tests
543 $this->mOldtext = $this->mOldRev->getText();
544 if ( $this->mOldtext === false ) {
545 return false;
546 }
547 }
548 if ( $this->mNewRev ) {
549 $this->mNewtext = $this->mNewRev->getText();
550 if ( $this->mNewtext === false ) {
551 return false;
552 }
553 }
554 return true;
555 }
556
557 /**
558 * Load the text of the new revision, not the old one
559 */
560 function loadNewText() {
561 if ( $this->mTextLoaded >= 1 ) {
562 return true;
563 } else {
564 $this->mTextLoaded = 1;
565 }
566 if ( !$this->loadRevisionData() ) {
567 return false;
568 }
569 $this->mNewtext = $this->mNewRev->getText();
570 return true;
571 }
572
573
574 }
575
576 // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3)
577 //
578 // Copyright (C) 2000, 2001 Geoffrey T. Dairiki <dairiki@dairiki.org>
579 // You may copy this code freely under the conditions of the GPL.
580 //
581
582 define('USE_ASSERTS', function_exists('assert'));
583
584 /**
585 * @todo document
586 * @access private
587 * @package MediaWiki
588 * @subpackage DifferenceEngine
589 */
590 class _DiffOp {
591 var $type;
592 var $orig;
593 var $closing;
594
595 function reverse() {
596 trigger_error('pure virtual', E_USER_ERROR);
597 }
598
599 function norig() {
600 return $this->orig ? sizeof($this->orig) : 0;
601 }
602
603 function nclosing() {
604 return $this->closing ? sizeof($this->closing) : 0;
605 }
606 }
607
608 /**
609 * @todo document
610 * @access private
611 * @package MediaWiki
612 * @subpackage DifferenceEngine
613 */
614 class _DiffOp_Copy extends _DiffOp {
615 var $type = 'copy';
616
617 function _DiffOp_Copy ($orig, $closing = false) {
618 if (!is_array($closing))
619 $closing = $orig;
620 $this->orig = $orig;
621 $this->closing = $closing;
622 }
623
624 function reverse() {
625 return new _DiffOp_Copy($this->closing, $this->orig);
626 }
627 }
628
629 /**
630 * @todo document
631 * @access private
632 * @package MediaWiki
633 * @subpackage DifferenceEngine
634 */
635 class _DiffOp_Delete extends _DiffOp {
636 var $type = 'delete';
637
638 function _DiffOp_Delete ($lines) {
639 $this->orig = $lines;
640 $this->closing = false;
641 }
642
643 function reverse() {
644 return new _DiffOp_Add($this->orig);
645 }
646 }
647
648 /**
649 * @todo document
650 * @access private
651 * @package MediaWiki
652 * @subpackage DifferenceEngine
653 */
654 class _DiffOp_Add extends _DiffOp {
655 var $type = 'add';
656
657 function _DiffOp_Add ($lines) {
658 $this->closing = $lines;
659 $this->orig = false;
660 }
661
662 function reverse() {
663 return new _DiffOp_Delete($this->closing);
664 }
665 }
666
667 /**
668 * @todo document
669 * @access private
670 * @package MediaWiki
671 * @subpackage DifferenceEngine
672 */
673 class _DiffOp_Change extends _DiffOp {
674 var $type = 'change';
675
676 function _DiffOp_Change ($orig, $closing) {
677 $this->orig = $orig;
678 $this->closing = $closing;
679 }
680
681 function reverse() {
682 return new _DiffOp_Change($this->closing, $this->orig);
683 }
684 }
685
686
687 /**
688 * Class used internally by Diff to actually compute the diffs.
689 *
690 * The algorithm used here is mostly lifted from the perl module
691 * Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
692 * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
693 *
694 * More ideas are taken from:
695 * http://www.ics.uci.edu/~eppstein/161/960229.html
696 *
697 * Some ideas are (and a bit of code) are from from analyze.c, from GNU
698 * diffutils-2.7, which can be found at:
699 * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
700 *
701 * closingly, some ideas (subdivision by NCHUNKS > 2, and some optimizations)
702 * are my own.
703 *
704 * Line length limits for robustness added by Tim Starling, 2005-08-31
705 *
706 * @author Geoffrey T. Dairiki, Tim Starling
707 * @access private
708 * @package MediaWiki
709 * @subpackage DifferenceEngine
710 */
711 class _DiffEngine
712 {
713 function diff ($from_lines, $to_lines) {
714 $fname = '_DiffEngine::diff';
715 wfProfileIn( $fname );
716
717 $n_from = sizeof($from_lines);
718 $n_to = sizeof($to_lines);
719
720 $this->xchanged = $this->ychanged = array();
721 $this->xv = $this->yv = array();
722 $this->xind = $this->yind = array();
723 unset($this->seq);
724 unset($this->in_seq);
725 unset($this->lcs);
726
727 // Skip leading common lines.
728 for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
729 if ($from_lines[$skip] !== $to_lines[$skip])
730 break;
731 $this->xchanged[$skip] = $this->ychanged[$skip] = false;
732 }
733 // Skip trailing common lines.
734 $xi = $n_from; $yi = $n_to;
735 for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
736 if ($from_lines[$xi] !== $to_lines[$yi])
737 break;
738 $this->xchanged[$xi] = $this->ychanged[$yi] = false;
739 }
740
741 // Ignore lines which do not exist in both files.
742 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
743 $xhash[$this->_line_hash($from_lines[$xi])] = 1;
744 }
745
746 for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
747 $line = $to_lines[$yi];
748 if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) )
749 continue;
750 $yhash[$this->_line_hash($line)] = 1;
751 $this->yv[] = $line;
752 $this->yind[] = $yi;
753 }
754 for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
755 $line = $from_lines[$xi];
756 if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) )
757 continue;
758 $this->xv[] = $line;
759 $this->xind[] = $xi;
760 }
761
762 // Find the LCS.
763 $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
764
765 // Merge edits when possible
766 $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
767 $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
768
769 // Compute the edit operations.
770 $edits = array();
771 $xi = $yi = 0;
772 while ($xi < $n_from || $yi < $n_to) {
773 USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]);
774 USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]);
775
776 // Skip matching "snake".
777 $copy = array();
778 while ( $xi < $n_from && $yi < $n_to
779 && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
780 $copy[] = $from_lines[$xi++];
781 ++$yi;
782 }
783 if ($copy)
784 $edits[] = new _DiffOp_Copy($copy);
785
786 // Find deletes & adds.
787 $delete = array();
788 while ($xi < $n_from && $this->xchanged[$xi])
789 $delete[] = $from_lines[$xi++];
790
791 $add = array();
792 while ($yi < $n_to && $this->ychanged[$yi])
793 $add[] = $to_lines[$yi++];
794
795 if ($delete && $add)
796 $edits[] = new _DiffOp_Change($delete, $add);
797 elseif ($delete)
798 $edits[] = new _DiffOp_Delete($delete);
799 elseif ($add)
800 $edits[] = new _DiffOp_Add($add);
801 }
802 wfProfileOut( $fname );
803 return $edits;
804 }
805
806 /**
807 * Returns the whole line if it's small enough, or the MD5 hash otherwise
808 */
809 function _line_hash( $line ) {
810 if ( strlen( $line ) > MAX_DIFF_XREF_LENGTH ) {
811 return md5( $line );
812 } else {
813 return $line;
814 }
815 }
816
817
818 /* Divide the Largest Common Subsequence (LCS) of the sequences
819 * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally
820 * sized segments.
821 *
822 * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an
823 * array of NCHUNKS+1 (X, Y) indexes giving the diving points between
824 * sub sequences. The first sub-sequence is contained in [X0, X1),
825 * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note
826 * that (X0, Y0) == (XOFF, YOFF) and
827 * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
828 *
829 * This function assumes that the first lines of the specified portions
830 * of the two files do not match, and likewise that the last lines do not
831 * match. The caller must trim matching lines from the beginning and end
832 * of the portions it is going to specify.
833 */
834 function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) {
835 $fname = '_DiffEngine::_diag';
836 wfProfileIn( $fname );
837 $flip = false;
838
839 if ($xlim - $xoff > $ylim - $yoff) {
840 // Things seems faster (I'm not sure I understand why)
841 // when the shortest sequence in X.
842 $flip = true;
843 list ($xoff, $xlim, $yoff, $ylim)
844 = array( $yoff, $ylim, $xoff, $xlim);
845 }
846
847 if ($flip)
848 for ($i = $ylim - 1; $i >= $yoff; $i--)
849 $ymatches[$this->xv[$i]][] = $i;
850 else
851 for ($i = $ylim - 1; $i >= $yoff; $i--)
852 $ymatches[$this->yv[$i]][] = $i;
853
854 $this->lcs = 0;
855 $this->seq[0]= $yoff - 1;
856 $this->in_seq = array();
857 $ymids[0] = array();
858
859 $numer = $xlim - $xoff + $nchunks - 1;
860 $x = $xoff;
861 for ($chunk = 0; $chunk < $nchunks; $chunk++) {
862 wfProfileIn( "$fname-chunk" );
863 if ($chunk > 0)
864 for ($i = 0; $i <= $this->lcs; $i++)
865 $ymids[$i][$chunk-1] = $this->seq[$i];
866
867 $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
868 for ( ; $x < $x1; $x++) {
869 $line = $flip ? $this->yv[$x] : $this->xv[$x];
870 if (empty($ymatches[$line]))
871 continue;
872 $matches = $ymatches[$line];
873 reset($matches);
874 while (list ($junk, $y) = each($matches))
875 if (empty($this->in_seq[$y])) {
876 $k = $this->_lcs_pos($y);
877 USE_ASSERTS && assert($k > 0);
878 $ymids[$k] = $ymids[$k-1];
879 break;
880 }
881 while (list ($junk, $y) = each($matches)) {
882 if ($y > $this->seq[$k-1]) {
883 USE_ASSERTS && assert($y < $this->seq[$k]);
884 // Optimization: this is a common case:
885 // next match is just replacing previous match.
886 $this->in_seq[$this->seq[$k]] = false;
887 $this->seq[$k] = $y;
888 $this->in_seq[$y] = 1;
889 } else if (empty($this->in_seq[$y])) {
890 $k = $this->_lcs_pos($y);
891 USE_ASSERTS && assert($k > 0);
892 $ymids[$k] = $ymids[$k-1];
893 }
894 }
895 }
896 wfProfileOut( "$fname-chunk" );
897 }
898
899 $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
900 $ymid = $ymids[$this->lcs];
901 for ($n = 0; $n < $nchunks - 1; $n++) {
902 $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
903 $y1 = $ymid[$n] + 1;
904 $seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
905 }
906 $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
907
908 wfProfileOut( $fname );
909 return array($this->lcs, $seps);
910 }
911
912 function _lcs_pos ($ypos) {
913 $fname = '_DiffEngine::_lcs_pos';
914 wfProfileIn( $fname );
915
916 $end = $this->lcs;
917 if ($end == 0 || $ypos > $this->seq[$end]) {
918 $this->seq[++$this->lcs] = $ypos;
919 $this->in_seq[$ypos] = 1;
920 wfProfileOut( $fname );
921 return $this->lcs;
922 }
923
924 $beg = 1;
925 while ($beg < $end) {
926 $mid = (int)(($beg + $end) / 2);
927 if ( $ypos > $this->seq[$mid] )
928 $beg = $mid + 1;
929 else
930 $end = $mid;
931 }
932
933 USE_ASSERTS && assert($ypos != $this->seq[$end]);
934
935 $this->in_seq[$this->seq[$end]] = false;
936 $this->seq[$end] = $ypos;
937 $this->in_seq[$ypos] = 1;
938 wfProfileOut( $fname );
939 return $end;
940 }
941
942 /* Find LCS of two sequences.
943 *
944 * The results are recorded in the vectors $this->{x,y}changed[], by
945 * storing a 1 in the element for each line that is an insertion
946 * or deletion (ie. is not in the LCS).
947 *
948 * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
949 *
950 * Note that XLIM, YLIM are exclusive bounds.
951 * All line numbers are origin-0 and discarded lines are not counted.
952 */
953 function _compareseq ($xoff, $xlim, $yoff, $ylim) {
954 $fname = '_DiffEngine::_compareseq';
955 wfProfileIn( $fname );
956
957 // Slide down the bottom initial diagonal.
958 while ($xoff < $xlim && $yoff < $ylim
959 && $this->xv[$xoff] == $this->yv[$yoff]) {
960 ++$xoff;
961 ++$yoff;
962 }
963
964 // Slide up the top initial diagonal.
965 while ($xlim > $xoff && $ylim > $yoff
966 && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
967 --$xlim;
968 --$ylim;
969 }
970
971 if ($xoff == $xlim || $yoff == $ylim)
972 $lcs = 0;
973 else {
974 // This is ad hoc but seems to work well.
975 //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5);
976 //$nchunks = max(2,min(8,(int)$nchunks));
977 $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
978 list ($lcs, $seps)
979 = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks);
980 }
981
982 if ($lcs == 0) {
983 // X and Y sequences have no common subsequence:
984 // mark all changed.
985 while ($yoff < $ylim)
986 $this->ychanged[$this->yind[$yoff++]] = 1;
987 while ($xoff < $xlim)
988 $this->xchanged[$this->xind[$xoff++]] = 1;
989 } else {
990 // Use the partitions to split this problem into subproblems.
991 reset($seps);
992 $pt1 = $seps[0];
993 while ($pt2 = next($seps)) {
994 $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
995 $pt1 = $pt2;
996 }
997 }
998 wfProfileOut( $fname );
999 }
1000
1001 /* Adjust inserts/deletes of identical lines to join changes
1002 * as much as possible.
1003 *
1004 * We do something when a run of changed lines include a
1005 * line at one end and has an excluded, identical line at the other.
1006 * We are free to choose which identical line is included.
1007 * `compareseq' usually chooses the one at the beginning,
1008 * but usually it is cleaner to consider the following identical line
1009 * to be the "change".
1010 *
1011 * This is extracted verbatim from analyze.c (GNU diffutils-2.7).
1012 */
1013 function _shift_boundaries ($lines, &$changed, $other_changed) {
1014 $fname = '_DiffEngine::_shift_boundaries';
1015 wfProfileIn( $fname );
1016 $i = 0;
1017 $j = 0;
1018
1019 USE_ASSERTS && assert('sizeof($lines) == sizeof($changed)');
1020 $len = sizeof($lines);
1021 $other_len = sizeof($other_changed);
1022
1023 while (1) {
1024 /*
1025 * Scan forwards to find beginning of another run of changes.
1026 * Also keep track of the corresponding point in the other file.
1027 *
1028 * Throughout this code, $i and $j are adjusted together so that
1029 * the first $i elements of $changed and the first $j elements
1030 * of $other_changed both contain the same number of zeros
1031 * (unchanged lines).
1032 * Furthermore, $j is always kept so that $j == $other_len or
1033 * $other_changed[$j] == false.
1034 */
1035 while ($j < $other_len && $other_changed[$j])
1036 $j++;
1037
1038 while ($i < $len && ! $changed[$i]) {
1039 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1040 $i++; $j++;
1041 while ($j < $other_len && $other_changed[$j])
1042 $j++;
1043 }
1044
1045 if ($i == $len)
1046 break;
1047
1048 $start = $i;
1049
1050 // Find the end of this run of changes.
1051 while (++$i < $len && $changed[$i])
1052 continue;
1053
1054 do {
1055 /*
1056 * Record the length of this run of changes, so that
1057 * we can later determine whether the run has grown.
1058 */
1059 $runlength = $i - $start;
1060
1061 /*
1062 * Move the changed region back, so long as the
1063 * previous unchanged line matches the last changed one.
1064 * This merges with previous changed regions.
1065 */
1066 while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
1067 $changed[--$start] = 1;
1068 $changed[--$i] = false;
1069 while ($start > 0 && $changed[$start - 1])
1070 $start--;
1071 USE_ASSERTS && assert('$j > 0');
1072 while ($other_changed[--$j])
1073 continue;
1074 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1075 }
1076
1077 /*
1078 * Set CORRESPONDING to the end of the changed run, at the last
1079 * point where it corresponds to a changed run in the other file.
1080 * CORRESPONDING == LEN means no such point has been found.
1081 */
1082 $corresponding = $j < $other_len ? $i : $len;
1083
1084 /*
1085 * Move the changed region forward, so long as the
1086 * first changed line matches the following unchanged one.
1087 * This merges with following changed regions.
1088 * Do this second, so that if there are no merges,
1089 * the changed region is moved forward as far as possible.
1090 */
1091 while ($i < $len && $lines[$start] == $lines[$i]) {
1092 $changed[$start++] = false;
1093 $changed[$i++] = 1;
1094 while ($i < $len && $changed[$i])
1095 $i++;
1096
1097 USE_ASSERTS && assert('$j < $other_len && ! $other_changed[$j]');
1098 $j++;
1099 if ($j < $other_len && $other_changed[$j]) {
1100 $corresponding = $i;
1101 while ($j < $other_len && $other_changed[$j])
1102 $j++;
1103 }
1104 }
1105 } while ($runlength != $i - $start);
1106
1107 /*
1108 * If possible, move the fully-merged run of changes
1109 * back to a corresponding run in the other file.
1110 */
1111 while ($corresponding < $i) {
1112 $changed[--$start] = 1;
1113 $changed[--$i] = 0;
1114 USE_ASSERTS && assert('$j > 0');
1115 while ($other_changed[--$j])
1116 continue;
1117 USE_ASSERTS && assert('$j >= 0 && !$other_changed[$j]');
1118 }
1119 }
1120 wfProfileOut( $fname );
1121 }
1122 }
1123
1124 /**
1125 * Class representing a 'diff' between two sequences of strings.
1126 * @todo document
1127 * @access private
1128 * @package MediaWiki
1129 * @subpackage DifferenceEngine
1130 */
1131 class Diff
1132 {
1133 var $edits;
1134
1135 /**
1136 * Constructor.
1137 * Computes diff between sequences of strings.
1138 *
1139 * @param $from_lines array An array of strings.
1140 * (Typically these are lines from a file.)
1141 * @param $to_lines array An array of strings.
1142 */
1143 function Diff($from_lines, $to_lines) {
1144 $eng = new _DiffEngine;
1145 $this->edits = $eng->diff($from_lines, $to_lines);
1146 //$this->_check($from_lines, $to_lines);
1147 }
1148
1149 /**
1150 * Compute reversed Diff.
1151 *
1152 * SYNOPSIS:
1153 *
1154 * $diff = new Diff($lines1, $lines2);
1155 * $rev = $diff->reverse();
1156 * @return object A Diff object representing the inverse of the
1157 * original diff.
1158 */
1159 function reverse () {
1160 $rev = $this;
1161 $rev->edits = array();
1162 foreach ($this->edits as $edit) {
1163 $rev->edits[] = $edit->reverse();
1164 }
1165 return $rev;
1166 }
1167
1168 /**
1169 * Check for empty diff.
1170 *
1171 * @return bool True iff two sequences were identical.
1172 */
1173 function isEmpty () {
1174 foreach ($this->edits as $edit) {
1175 if ($edit->type != 'copy')
1176 return false;
1177 }
1178 return true;
1179 }
1180
1181 /**
1182 * Compute the length of the Longest Common Subsequence (LCS).
1183 *
1184 * This is mostly for diagnostic purposed.
1185 *
1186 * @return int The length of the LCS.
1187 */
1188 function lcs () {
1189 $lcs = 0;
1190 foreach ($this->edits as $edit) {
1191 if ($edit->type == 'copy')
1192 $lcs += sizeof($edit->orig);
1193 }
1194 return $lcs;
1195 }
1196
1197 /**
1198 * Get the original set of lines.
1199 *
1200 * This reconstructs the $from_lines parameter passed to the
1201 * constructor.
1202 *
1203 * @return array The original sequence of strings.
1204 */
1205 function orig() {
1206 $lines = array();
1207
1208 foreach ($this->edits as $edit) {
1209 if ($edit->orig)
1210 array_splice($lines, sizeof($lines), 0, $edit->orig);
1211 }
1212 return $lines;
1213 }
1214
1215 /**
1216 * Get the closing set of lines.
1217 *
1218 * This reconstructs the $to_lines parameter passed to the
1219 * constructor.
1220 *
1221 * @return array The sequence of strings.
1222 */
1223 function closing() {
1224 $lines = array();
1225
1226 foreach ($this->edits as $edit) {
1227 if ($edit->closing)
1228 array_splice($lines, sizeof($lines), 0, $edit->closing);
1229 }
1230 return $lines;
1231 }
1232
1233 /**
1234 * Check a Diff for validity.
1235 *
1236 * This is here only for debugging purposes.
1237 */
1238 function _check ($from_lines, $to_lines) {
1239 $fname = 'Diff::_check';
1240 wfProfileIn( $fname );
1241 if (serialize($from_lines) != serialize($this->orig()))
1242 trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
1243 if (serialize($to_lines) != serialize($this->closing()))
1244 trigger_error("Reconstructed closing doesn't match", E_USER_ERROR);
1245
1246 $rev = $this->reverse();
1247 if (serialize($to_lines) != serialize($rev->orig()))
1248 trigger_error("Reversed original doesn't match", E_USER_ERROR);
1249 if (serialize($from_lines) != serialize($rev->closing()))
1250 trigger_error("Reversed closing doesn't match", E_USER_ERROR);
1251
1252
1253 $prevtype = 'none';
1254 foreach ($this->edits as $edit) {
1255 if ( $prevtype == $edit->type )
1256 trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
1257 $prevtype = $edit->type;
1258 }
1259
1260 $lcs = $this->lcs();
1261 trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE);
1262 wfProfileOut( $fname );
1263 }
1264 }
1265
1266 /**
1267 * FIXME: bad name.
1268 * @todo document
1269 * @access private
1270 * @package MediaWiki
1271 * @subpackage DifferenceEngine
1272 */
1273 class MappedDiff extends Diff
1274 {
1275 /**
1276 * Constructor.
1277 *
1278 * Computes diff between sequences of strings.
1279 *
1280 * This can be used to compute things like
1281 * case-insensitve diffs, or diffs which ignore
1282 * changes in white-space.
1283 *
1284 * @param $from_lines array An array of strings.
1285 * (Typically these are lines from a file.)
1286 *
1287 * @param $to_lines array An array of strings.
1288 *
1289 * @param $mapped_from_lines array This array should
1290 * have the same size number of elements as $from_lines.
1291 * The elements in $mapped_from_lines and
1292 * $mapped_to_lines are what is actually compared
1293 * when computing the diff.
1294 *
1295 * @param $mapped_to_lines array This array should
1296 * have the same number of elements as $to_lines.
1297 */
1298 function MappedDiff($from_lines, $to_lines,
1299 $mapped_from_lines, $mapped_to_lines) {
1300 $fname = 'MappedDiff::MappedDiff';
1301 wfProfileIn( $fname );
1302
1303 assert(sizeof($from_lines) == sizeof($mapped_from_lines));
1304 assert(sizeof($to_lines) == sizeof($mapped_to_lines));
1305
1306 $this->Diff($mapped_from_lines, $mapped_to_lines);
1307
1308 $xi = $yi = 0;
1309 for ($i = 0; $i < sizeof($this->edits); $i++) {
1310 $orig = &$this->edits[$i]->orig;
1311 if (is_array($orig)) {
1312 $orig = array_slice($from_lines, $xi, sizeof($orig));
1313 $xi += sizeof($orig);
1314 }
1315
1316 $closing = &$this->edits[$i]->closing;
1317 if (is_array($closing)) {
1318 $closing = array_slice($to_lines, $yi, sizeof($closing));
1319 $yi += sizeof($closing);
1320 }
1321 }
1322 wfProfileOut( $fname );
1323 }
1324 }
1325
1326 /**
1327 * A class to format Diffs
1328 *
1329 * This class formats the diff in classic diff format.
1330 * It is intended that this class be customized via inheritance,
1331 * to obtain fancier outputs.
1332 * @todo document
1333 * @access private
1334 * @package MediaWiki
1335 * @subpackage DifferenceEngine
1336 */
1337 class DiffFormatter
1338 {
1339 /**
1340 * Number of leading context "lines" to preserve.
1341 *
1342 * This should be left at zero for this class, but subclasses
1343 * may want to set this to other values.
1344 */
1345 var $leading_context_lines = 0;
1346
1347 /**
1348 * Number of trailing context "lines" to preserve.
1349 *
1350 * This should be left at zero for this class, but subclasses
1351 * may want to set this to other values.
1352 */
1353 var $trailing_context_lines = 0;
1354
1355 /**
1356 * Format a diff.
1357 *
1358 * @param $diff object A Diff object.
1359 * @return string The formatted output.
1360 */
1361 function format($diff) {
1362 $fname = 'DiffFormatter::format';
1363 wfProfileIn( $fname );
1364
1365 $xi = $yi = 1;
1366 $block = false;
1367 $context = array();
1368
1369 $nlead = $this->leading_context_lines;
1370 $ntrail = $this->trailing_context_lines;
1371
1372 $this->_start_diff();
1373
1374 foreach ($diff->edits as $edit) {
1375 if ($edit->type == 'copy') {
1376 if (is_array($block)) {
1377 if (sizeof($edit->orig) <= $nlead + $ntrail) {
1378 $block[] = $edit;
1379 }
1380 else{
1381 if ($ntrail) {
1382 $context = array_slice($edit->orig, 0, $ntrail);
1383 $block[] = new _DiffOp_Copy($context);
1384 }
1385 $this->_block($x0, $ntrail + $xi - $x0,
1386 $y0, $ntrail + $yi - $y0,
1387 $block);
1388 $block = false;
1389 }
1390 }
1391 $context = $edit->orig;
1392 }
1393 else {
1394 if (! is_array($block)) {
1395 $context = array_slice($context, sizeof($context) - $nlead);
1396 $x0 = $xi - sizeof($context);
1397 $y0 = $yi - sizeof($context);
1398 $block = array();
1399 if ($context)
1400 $block[] = new _DiffOp_Copy($context);
1401 }
1402 $block[] = $edit;
1403 }
1404
1405 if ($edit->orig)
1406 $xi += sizeof($edit->orig);
1407 if ($edit->closing)
1408 $yi += sizeof($edit->closing);
1409 }
1410
1411 if (is_array($block))
1412 $this->_block($x0, $xi - $x0,
1413 $y0, $yi - $y0,
1414 $block);
1415
1416 $end = $this->_end_diff();
1417 wfProfileOut( $fname );
1418 return $end;
1419 }
1420
1421 function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) {
1422 $fname = 'DiffFormatter::_block';
1423 wfProfileIn( $fname );
1424 $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen));
1425 foreach ($edits as $edit) {
1426 if ($edit->type == 'copy')
1427 $this->_context($edit->orig);
1428 elseif ($edit->type == 'add')
1429 $this->_added($edit->closing);
1430 elseif ($edit->type == 'delete')
1431 $this->_deleted($edit->orig);
1432 elseif ($edit->type == 'change')
1433 $this->_changed($edit->orig, $edit->closing);
1434 else
1435 trigger_error('Unknown edit type', E_USER_ERROR);
1436 }
1437 $this->_end_block();
1438 wfProfileOut( $fname );
1439 }
1440
1441 function _start_diff() {
1442 ob_start();
1443 }
1444
1445 function _end_diff() {
1446 $val = ob_get_contents();
1447 ob_end_clean();
1448 return $val;
1449 }
1450
1451 function _block_header($xbeg, $xlen, $ybeg, $ylen) {
1452 if ($xlen > 1)
1453 $xbeg .= "," . ($xbeg + $xlen - 1);
1454 if ($ylen > 1)
1455 $ybeg .= "," . ($ybeg + $ylen - 1);
1456
1457 return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
1458 }
1459
1460 function _start_block($header) {
1461 echo $header;
1462 }
1463
1464 function _end_block() {
1465 }
1466
1467 function _lines($lines, $prefix = ' ') {
1468 foreach ($lines as $line)
1469 echo "$prefix $line\n";
1470 }
1471
1472 function _context($lines) {
1473 $this->_lines($lines);
1474 }
1475
1476 function _added($lines) {
1477 $this->_lines($lines, '>');
1478 }
1479 function _deleted($lines) {
1480 $this->_lines($lines, '<');
1481 }
1482
1483 function _changed($orig, $closing) {
1484 $this->_deleted($orig);
1485 echo "---\n";
1486 $this->_added($closing);
1487 }
1488 }
1489
1490
1491 /**
1492 * Additions by Axel Boldt follow, partly taken from diff.php, phpwiki-1.3.3
1493 *
1494 */
1495
1496 define('NBSP', '&#160;'); // iso-8859-x non-breaking space.
1497
1498 /**
1499 * @todo document
1500 * @access private
1501 * @package MediaWiki
1502 * @subpackage DifferenceEngine
1503 */
1504 class _HWLDF_WordAccumulator {
1505 function _HWLDF_WordAccumulator () {
1506 $this->_lines = array();
1507 $this->_line = '';
1508 $this->_group = '';
1509 $this->_tag = '';
1510 }
1511
1512 function _flushGroup ($new_tag) {
1513 if ($this->_group !== '') {
1514 if ($this->_tag == 'mark')
1515 $this->_line .= '<span class="diffchange">' .
1516 htmlspecialchars ( $this->_group ) . '</span>';
1517 else
1518 $this->_line .= htmlspecialchars ( $this->_group );
1519 }
1520 $this->_group = '';
1521 $this->_tag = $new_tag;
1522 }
1523
1524 function _flushLine ($new_tag) {
1525 $this->_flushGroup($new_tag);
1526 if ($this->_line != '')
1527 array_push ( $this->_lines, $this->_line );
1528 else
1529 # make empty lines visible by inserting an NBSP
1530 array_push ( $this->_lines, NBSP );
1531 $this->_line = '';
1532 }
1533
1534 function addWords ($words, $tag = '') {
1535 if ($tag != $this->_tag)
1536 $this->_flushGroup($tag);
1537
1538 foreach ($words as $word) {
1539 // new-line should only come as first char of word.
1540 if ($word == '')
1541 continue;
1542 if ($word[0] == "\n") {
1543 $this->_flushLine($tag);
1544 $word = substr($word, 1);
1545 }
1546 assert(!strstr($word, "\n"));
1547 $this->_group .= $word;
1548 }
1549 }
1550
1551 function getLines() {
1552 $this->_flushLine('~done');
1553 return $this->_lines;
1554 }
1555 }
1556
1557 /**
1558 * @todo document
1559 * @access private
1560 * @package MediaWiki
1561 * @subpackage DifferenceEngine
1562 */
1563 class WordLevelDiff extends MappedDiff
1564 {
1565 function WordLevelDiff ($orig_lines, $closing_lines) {
1566 $fname = 'WordLevelDiff::WordLevelDiff';
1567 wfProfileIn( $fname );
1568
1569 list ($orig_words, $orig_stripped) = $this->_split($orig_lines);
1570 list ($closing_words, $closing_stripped) = $this->_split($closing_lines);
1571
1572 $this->MappedDiff($orig_words, $closing_words,
1573 $orig_stripped, $closing_stripped);
1574 wfProfileOut( $fname );
1575 }
1576
1577 function _split($lines) {
1578 $fname = 'WordLevelDiff::_split';
1579 wfProfileIn( $fname );
1580
1581 $words = array();
1582 $stripped = array();
1583 $first = true;
1584 foreach ( $lines as $line ) {
1585 # If the line is too long, just pretend the entire line is one big word
1586 # This prevents resource exhaustion problems
1587 if ( $first ) {
1588 $first = false;
1589 } else {
1590 $words[] = "\n";
1591 $stripped[] = "\n";
1592 }
1593 if ( strlen( $line ) > MAX_DIFF_LINE ) {
1594 $words[] = $line;
1595 $stripped[] = $line;
1596 } else {
1597 if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs',
1598 $line, $m))
1599 {
1600 $words = array_merge( $words, $m[0] );
1601 $stripped = array_merge( $stripped, $m[1] );
1602 }
1603 }
1604 }
1605 wfProfileOut( $fname );
1606 return array($words, $stripped);
1607 }
1608
1609 function orig () {
1610 $fname = 'WordLevelDiff::orig';
1611 wfProfileIn( $fname );
1612 $orig = new _HWLDF_WordAccumulator;
1613
1614 foreach ($this->edits as $edit) {
1615 if ($edit->type == 'copy')
1616 $orig->addWords($edit->orig);
1617 elseif ($edit->orig)
1618 $orig->addWords($edit->orig, 'mark');
1619 }
1620 $lines = $orig->getLines();
1621 wfProfileOut( $fname );
1622 return $lines;
1623 }
1624
1625 function closing () {
1626 $fname = 'WordLevelDiff::closing';
1627 wfProfileIn( $fname );
1628 $closing = new _HWLDF_WordAccumulator;
1629
1630 foreach ($this->edits as $edit) {
1631 if ($edit->type == 'copy')
1632 $closing->addWords($edit->closing);
1633 elseif ($edit->closing)
1634 $closing->addWords($edit->closing, 'mark');
1635 }
1636 $lines = $closing->getLines();
1637 wfProfileOut( $fname );
1638 return $lines;
1639 }
1640 }
1641
1642 /**
1643 * Wikipedia Table style diff formatter.
1644 * @todo document
1645 * @access private
1646 * @package MediaWiki
1647 * @subpackage DifferenceEngine
1648 */
1649 class TableDiffFormatter extends DiffFormatter
1650 {
1651 function TableDiffFormatter() {
1652 $this->leading_context_lines = 2;
1653 $this->trailing_context_lines = 2;
1654 }
1655
1656 function _block_header( $xbeg, $xlen, $ybeg, $ylen ) {
1657 $r = '<tr><td colspan="2" align="left"><strong><!--LINE '.$xbeg."--></strong></td>\n" .
1658 '<td colspan="2" align="left"><strong><!--LINE '.$ybeg."--></strong></td></tr>\n";
1659 return $r;
1660 }
1661
1662 function _start_block( $header ) {
1663 echo $header;
1664 }
1665
1666 function _end_block() {
1667 }
1668
1669 function _lines( $lines, $prefix=' ', $color='white' ) {
1670 }
1671
1672 # HTML-escape parameter before calling this
1673 function addedLine( $line ) {
1674 return "<td>+</td><td class='diff-addedline'>{$line}</td>";
1675 }
1676
1677 # HTML-escape parameter before calling this
1678 function deletedLine( $line ) {
1679 return "<td>-</td><td class='diff-deletedline'>{$line}</td>";
1680 }
1681
1682 # HTML-escape parameter before calling this
1683 function contextLine( $line ) {
1684 return "<td> </td><td class='diff-context'>{$line}</td>";
1685 }
1686
1687 function emptyLine() {
1688 return '<td colspan="2">&nbsp;</td>';
1689 }
1690
1691 function _added( $lines ) {
1692 foreach ($lines as $line) {
1693 echo '<tr>' . $this->emptyLine() .
1694 $this->addedLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1695 }
1696 }
1697
1698 function _deleted($lines) {
1699 foreach ($lines as $line) {
1700 echo '<tr>' . $this->deletedLine( htmlspecialchars ( $line ) ) .
1701 $this->emptyLine() . "</tr>\n";
1702 }
1703 }
1704
1705 function _context( $lines ) {
1706 foreach ($lines as $line) {
1707 echo '<tr>' .
1708 $this->contextLine( htmlspecialchars ( $line ) ) .
1709 $this->contextLine( htmlspecialchars ( $line ) ) . "</tr>\n";
1710 }
1711 }
1712
1713 function _changed( $orig, $closing ) {
1714 $fname = 'TableDiffFormatter::_changed';
1715 wfProfileIn( $fname );
1716
1717 $diff = new WordLevelDiff( $orig, $closing );
1718 $del = $diff->orig();
1719 $add = $diff->closing();
1720
1721 # Notice that WordLevelDiff returns HTML-escaped output.
1722 # Hence, we will be calling addedLine/deletedLine without HTML-escaping.
1723
1724 while ( $line = array_shift( $del ) ) {
1725 $aline = array_shift( $add );
1726 echo '<tr>' . $this->deletedLine( $line ) .
1727 $this->addedLine( $aline ) . "</tr>\n";
1728 }
1729 foreach ($add as $line) { # If any leftovers
1730 echo '<tr>' . $this->emptyLine() .
1731 $this->addedLine( $line ) . "</tr>\n";
1732 }
1733 wfProfileOut( $fname );
1734 }
1735 }
1736
1737 ?>